import React from 'react';
import {
    View,
    Text,
    ScrollView,
    TextInput,
    TouchableOpacity, Image, ImageBackground, Dimensions, StyleSheet, FlatList,
} from 'react-native';
import {
    InputItem,
    List,
    Switch,
    ActionSheet,
    DatePicker,
    TextareaItem,
    Button,
    Steps,
} from '@ant-design/react-native';
import Dict from '../../../common/Dict';
import FormItem from "../../../common/components/FormItem";
import FormRadioItem from "../../../common/components/FormRadioItem";
import GlobalStyles from "../../../common/styles/GlobalStyles";
import PickerViewModalCas from '../../../common/components/PickerViewModalCas';
import StorageUtil from '../../../utils/StorageUtil';
import {Constant} from '../../../common/Constant';
import Utils from '../../../utils/Utils';
import {BASE_URL} from '../../../common/BASE_URL';
import HttpUtils from "../../../expand/dao/HttpUtils";
import ToastUtil from "../../../utils/ToastUtil";
import TextInputItem from "../../../common/components/inputItem";
import CustomAlertDialog  from "../../../common/components/CustomAlertDialog"

let Step = Steps.Step;

let screenWidth = Dimensions.get('window').width;

let queryCheckTypeListUrl =  BASE_URL.apiBaseUrl + '/api/checkType/list'
let queryXunchaListUrl = BASE_URL.apiBaseUrl + '/api/checkItems'
let queryDocumentType = BASE_URL.apiBaseUrl + '/api/flowLink/initLink'
let getFlowLinkById = BASE_URL.apiBaseUrl + '/api/flowLink/findById'
let getFlowLinkList = BASE_URL.apiBaseUrl + '/api/flowLink/list'
// 常用短语
let getShortMsgList = BASE_URL.apiBaseUrl + '/api/commonPhrases/list'
// 所有角色
let getAllRole = BASE_URL.apiBaseUrl + '/api/roles/all'
// 所有人员
let getAllOfficer = BASE_URL.apiBaseUrl + '/api/enforcementOfficer/noDataScopes'
// 按钮
let getBtnInfoUrl = BASE_URL.apiBaseUrl + '/api/flowLinkHandle/findById'
// 办理记录
let getCaseActionRecordUrl = BASE_URL.apiBaseUrl + '/api/caseActionRecord/group'
let getAcceptActionRecordUrl = BASE_URL.apiBaseUrl + '/api/acceptActionRecord/group'
let getInspectionActionRecordUrl = BASE_URL.apiBaseUrl + '/api/inspectionActionRecord/group'
let getDeptUrl = BASE_URL.apiBaseUrl + '/api/dept/ownSuperior'
let getNextPerson = BASE_URL.apiBaseUrl +"/api/enforcementOfficer/ownOrganization"
let noDataScopes = BASE_URL.apiBaseUrl +"/api/enforcementOfficer/noDataScopes"

export default class CaseDocument extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            NextRow:{},
            documentType: '2',// 文书类型 1案件文书，2制作文书
            documentList: [{id: 1},{id: 2},{id: 3}],
            documentBtnList: [],
            activeBtns: [],
            sexDict: [],
            idTypeDict: [],
            nextLinks:null,
            checkTypeList: [],
            xunchaList: [],
            showDatePicker: false,
            // 角色、用户、部门
            roleSelectList: [], // 环节角色选项
            officerSelectList: [], // 环节执法员选项
            deptSelectList: [], // 环节部门选项

            cacheFlowLink: {},// 缓存步骤对象
            cacheNextLinkList: [],// 缓存
            // 巡查任务表单内容
            inspectionPendingMatter: {
                nextHandlerDeptList: [], // 部门限制选项 item.depts
                nextHandlerRoleList: [], // 角色限制选项 item.roles
                nextHandlerOfficerList: [], // 执法人员限制选项 item.officers
                nextHandlerDeptIds: [],
                nextHandlerDeptName: [],
                nextHandlerRoleIds: [],
                nextHandlerOfficerIds: [],
                nextHandlerOfficerNames: '',
                caseActionRecord: {
                    nextHandlerDepts: '',
                    nextHandlerRoles: '',
                    nextHandlerOfficers: '',
                    stateId: '',
                    linkId: '',
                    linkName: '',
                    linkHandleName: '',
                    handlerOpinions: ''
                }
            },
            casePendingMatter: {
                handleType: '',
                id: '',
                stateId: '',
                linkId: '',
                linkName: '',
                timeLimit: '',
                // 页面选择使用
                nextHandlerDeptList: [], // 部门限制选项 item.depts
                nextHandlerRoleList: [], // 角色限制选项 item.roles
                nextHandlerOfficerList: [], // 执法人员限制选项 item.officers
                // 选中的数据
                nextHandlerDeptIds: [],
                nextHandlerRoleIds: [],
                nextHandlerDeptName: '',
                nextHandlerRoleName: '',
                nextHandlerOfficerIds: [],
                isBranch: '',
                caseActionRecord: {
                    nextHandlerDepts: '',
                    nextHandlerRoles: '',
                    nextHandlerOfficers: '',
                    stateId: '',
                    linkId: '',
                    linkName: '',
                    linkHandleName: '',
                    handlerOpinions: ''
                }
            },
            caseInfoVo: {

            },
            document: {

            },
            actionRecords: [], // 办理操作记录
            shortMsgList:[],
            showTypePop:false,
            DeptArr:[],
            nextHandlerOfficerList:[]
        };
        this._initDeptTree()
    }


    async componentDidMount(){
        // let gender = await Dict.getDict('dict_gender')
        // let idType = await Dict.getDict('id_type')
        // this._initDeptTree()
        this.initDocumentType()
        this.initRoleAndOfficer()
        this.initActionRecords()
        this.initShortMsg()
    }

    //获取下环节处理人
    _avoidNextPerson(){
        let deptIds=this.state.casePendingMatter.nextHandlerDeptIds
        let roleIds=this.state.casePendingMatter.nextHandlerRoleIds
        let ids=this.state.casePendingMatter.nextHandlerOfficerList.map((item)=>item.officerId)
        let query={
            deptIds:deptIds&&deptIds.length>0?deptIds.join(","):'',
            roleIds:roleIds&&roleIds.length>0?roleIds.join(","):'',
            ids:ids&&ids.length>0?ids.join(","):'',
        }
        HttpUtils.request({
            url: getNextPerson,
            params:query
        }).then(res=>{
            this.setState({
                nextHandlerOfficerList:res
            })
        })
        
    }
    
    //获取部门树结构
    async  _initDeptTree(){
        let key = ToastUtil.loading('加载中...')
      await  HttpUtils.request({
            url: getDeptUrl
        }).then(res=>{
            this.setState({
                DeptArr:res.content
            })
        }).finally(()=>ToastUtil.remove(key))
        return Promise.resolve([])
    }


    initActionRecords(){
        let {type, caseCode} = this.props
        let url = '';
        if(type === 'caseInfo'){
            url = getCaseActionRecordUrl;
        }else if(type === 'clue'){
            url = getAcceptActionRecordUrl;
        }else if(type === 'inspection'){
            url = getInspectionActionRecordUrl;
        }
        if(!url) return
        HttpUtils.request({
            url: url,
            params: {caseCode: caseCode}
        }).then(res=>{
            if(res && !res.status){
                this.setState({
                    actionRecords: res
                })
            }
        }).catch(e=>{
            console.log(e)
        })
    }
    initRoleAndOfficer(){
        let {submitType, reportType} = this.props
        HttpUtils.request({
            url: getAllRole
        }).then(res=>{
            this.state.roleSelectList = res
            // this.setState({
            //     roleSelectList:res.res
            // })
        })
        let key = ToastUtil.loading('加载中...')
        HttpUtils.request({
            url: getAllOfficer
        }).then(res=>{
            ToastUtil.remove(key)
            this.state.officerSelectList = res.content
            // this.setState({
            //     officerSelectList:res.content
            // })
            if(submitType && submitType === 'post' && reportType !== 'clue'){
                this.initCaseBtn()
            }
        }).catch(e=>{
            console.log(e);
            ToastUtil.remove(key)
        })
    }

    initShortMsg(){
        HttpUtils.request({
            url: getShortMsgList,
            params:{}
        }).then(item=>{
            this.setState({
                shortMsgList:item
            })
        }).catch(e=>{
            console.log(e)
        })
    }

    initCaseBtn(){
        // 默认巡查任务信息
        HttpUtils.request({
            url: getBtnInfoUrl,
            params:{ id: 321 }
        }).then(item=>{
            let {id,nextLinks} = item
            if(this.state.activeBtns.includes(id)){
                //
            }else{
                this.state.activeBtns = [id]
                this.props.hadCaseDeal({id})
                // 判断是否存在下一步环节
                if(nextLinks){
                    this.initHandleLinkList(nextLinks,true);
                }else {
                    this.state.cacheNextLinkList = []
                }
                let copyItem = JSON.parse(JSON.stringify(item))
                copyItem.id = ''
                this.setState({
                    nextLinks:nextLinks,
                    activeBtns: this.state.activeBtns,
                    inspectionPendingMatter: {
                        ...this.state.inspectionPendingMatter,
                        caseActionRecord: {},
                        ...copyItem,
                    },
                    casePendingMatter: {
                        ...this.state.casePendingMatter,
                        ...copyItem,
                    }
                },()=>{
                    this.props.onChange && this.props.onChange({
                        inspectionPendingMatter: this.state.inspectionPendingMatter,
                        casePendingMatter: this.state.casePendingMatter
                    })
                })

            }
        }).catch(e=>{
            console.log(e)
        })
    }

    initDocumentType(){
        let {submitType, reportType, linkId} = this.props
        if(submitType && submitType === 'post'){
            let flowType = 1
            if(reportType === 'clue'){
                flowType = 2
            }
            HttpUtils.request({
                url: queryDocumentType,
                params: {flowType: flowType}
            }).then(res=>{
                // this.state.documentBtnList = res.children
                if(res){
                    // 缓存对象
                    this.setState({
                        cacheFlowLink: res,
                        documentBtnList: res.children
                    })
                }
            }).catch(e=>{
                console.log(e)
            })
        }else {
            HttpUtils.request({
                url: getFlowLinkById,
                params: {id: linkId}
            }).then(res=>{
                // this.state.documentBtnList = res.children
                if(res){
                    // 缓存对象
                    // this.state.cacheFlowLink = res
                    this.setState({
                        cacheFlowLink: res,
                        documentBtnList: res.children
                    })
                }
            }).catch(e=>{
                console.log(e)
            })
        }

    }

    initHandleLinkList(links, flag){ //第二步
        HttpUtils.request({
            url: getFlowLinkList,
            params: {ids: links}
        }).then(res=>{
            // 缓存
            if(flag){
            }
            this.state.cacheNextLinkList = res
            let {cacheFlowLink,cacheNextLinkList,casePendingMatter,inspectionPendingMatter,roleSelectList,officerSelectList,NextRow} = this.state
            let {handleType} = casePendingMatter
            let obj = {
                stateId: cacheFlowLink.stateId, // 获取当前操作 阶段
                linkId: cacheFlowLink.id, // 获取当前操作 环节
                linkName: cacheFlowLink.name, // 获取当前操作, 环节名称
                linkHandleName: casePendingMatter.name, // 获取当前操作，处理方式
                linkHandleId: casePendingMatter.id
            }
            if(handleType === 2){
                // todo
            }else{
                let item = cacheNextLinkList[0]
                if(!item) return
                HttpUtils.request({
                    url: noDataScopes,
                    params:{ids:item.officers||''}
                }).then(res=>{
                    let officeroptions2=[]
                    let officerRecord=[]
                    if(item.officers){
                        officeroptions2=res.content
                        officerRecord=res.content.map(it=>it.name)
                    }
                    let isBranch = !this.props.pendingMattersId? 0: null
                    // 角色
                    let rolesVal = item.roles?(item.roles.split(",").map((id) => parseInt(id))): []
                    let roleoptions2 = [];
                    for (let i = 0, len = rolesVal.length; i < len; i++) {
                        for (let j = 0, len2 = roleSelectList.length; j < len2; j++) {
                            if (rolesVal[i] === roleSelectList[j].id) {
                                roleoptions2.push(roleSelectList[j]);
                                break;
                            }
                        }
                    }
                    // // 人员
                    // let officersVal = item.officers?item.officers.split(",").map((id) => parseInt(id)): []
                    // let officeroptions2 = [];
                    // let officerRecord = [];
                    
                    // if(flag){
                    //     for (let j = 0, len2 = officerSelectList.length; j < len2; j++) {
                    //         officeroptions2.push(officerSelectList[j]);
                    //         officerRecord.push(officerSelectList[j].name);
                    //     }
                    // }else{
                    //     for (let i = 0, len = officersVal.length; i < len; i++) {
                    //         for (let j = 0, len2 = officerSelectList.length; j < len2; j++) {
                    //             if (officersVal[i] === officerSelectList[j].officerId) {
                    //                 officeroptions2.push(officerSelectList[j]);
                    //                 officerRecord.push(officerSelectList[j].name);
                    //                 break;
                    //             }
                    //         }
                    //     }
                    // }
    
                    let stateObj2 = flag?inspectionPendingMatter:casePendingMatter
                    let caseActionRecord = {
                        nextHandlerDepts: item.depts,
                        nextHandlerRoles: item.roles,
                        nextHandlerOfficers: officerRecord.toString(),
                        stateId: cacheFlowLink.stateId, // 获取当前操作 阶段
                        linkId: cacheFlowLink.id, // 获取当前操作 环节
                        linkName: cacheFlowLink.name, // 获取当前操作, 环节名称
                        linkHandleName: stateObj2.name, // 获取当前操作，处理方式
                        linkHandleId: NextRow.id,
                        handlerOpinions: ""
                    };
    
                    let stateObj = flag?'inspectionPendingMatter':'casePendingMatter'
                    this.setState({
                        [stateObj]:{
                            ...this.state[stateObj],
                            id: this.props.pendingMattersId,// 父页面传递过来
                            stateId: item.stateId,
                            linkId: item.id,
                            linkName: item.name,
                            timeLimit: item.timeLimit,
                            nextHandlerDeptList: [], // 部门限制选项 item.depts
                            nextHandlerRoleList: roleoptions2, // 角色限制选项 item.roles
                            nextHandlerOfficerList: officeroptions2, // 执法人员限制选项 item.officers
                            nextHandlerDeptIds: [],
                            nextHandlerRoleIds: [],
                            nextHandlerOfficerIds: [],
                            nextHandlerOfficerNames: '',
                            isBranch: isBranch,
                            caseActionRecord: caseActionRecord
                        }
                    },()=>{
                        this.props.onChange && this.props.onChange({
                            inspectionPendingMatter: this.state.inspectionPendingMatter,
                            casePendingMatter: this.state.casePendingMatter
                        })
                    })
                })
            }
        })
    }
    _changeActiveBtns(item){ //第一步
        let {type} = this.props
        let {id,nextLinks,name} = item
        this.setState({
            NextRow:item,
        })
        if(this.state.activeBtns.includes(id)){
            // let idx = this.state.activeBtns.indexOf(id)
            // this.state.activeBtns.splice(idx,1)
        }else{
            this.state.activeBtns = [id]
            this.props.hadCaseDeal(id)
            // 判断是否存在下一步环节
            let nextStepObj = null
            if(nextLinks){
                this.initHandleLinkList(nextLinks);
            }else{ // 最后一步环节
                // caseActionRecord
                let {cacheFlowLink} = this.state
                nextStepObj = {
                    stateId: cacheFlowLink.stateId,
                    linkId: cacheFlowLink.id,
                    linkName: cacheFlowLink.name,
                    linkHandleName: name,
                    handlerOpinions: "",
                }
                // let flowLink = this.flowLink; // 获取当前操作, 环节名称
                // let linkHandleName = this.flowLinkHandle.name; // 获取当前操作，处理方式
                // id = this.pendingMattersId;
            }
            let copyItem = JSON.parse(JSON.stringify(item))
            copyItem.linkHandleName = copyItem.name
            copyItem.id = ''
            this.setState({
                cacheNextLinkList: [],
                nextLinks:nextLinks,
                activeBtns: this.state.activeBtns,
                casePendingMatter: {
                    ...this.state.casePendingMatter,
                    id: this.props.pendingMattersId,// 父页面传递过来
                    stateId: null,
                    linkId: null,
                    linkName: '',
                    timeLimit: null,
                    nextHandlerOfficerList: [],
                    caseActionRecord: nextStepObj?nextStepObj:this.state.casePendingMatter,
                    ...copyItem,
                }
            },()=>{
                this.props.onChange && this.props.onChange({
                    inspectionPendingMatter: this.state.inspectionPendingMatter,
                    casePendingMatter: this.state.casePendingMatter
                })
            })

        }

    }
    _renderDealLog(){
        let {actionRecords} = this.state;
        let views = []
        if(actionRecords && actionRecords.length > 0){
            let list = actionRecords[0].list
            // [{"applicationTime": 1627308319000,
            // "caseCode": "51152420210000101131", "caseTextId": null,
            // "currentHandler": {"administrativeQualificationCertificateNumber": "08260114",
            // "isOnline": false, "latitude": 28.58838, "longitude": 104.93003, "name": "李小军", "officerId": 20},
            // "currentHandlerDept": 36, "currentHandlerId": 20, "expireTime": 1627358384000,
            // "handlerOpinions": "测试", "id": 106, "isBranch": 0, "isEffective": null, "linkHandleId": null,
            // "linkHandleName": "建议立案", "linkId": 1, "linkName": "检查上报", "nextHandlerDepts": "40,41,42,43,44", "nextHandlerOfficers": "刘艳,李旭东,罗龙,邓益", "nextHandlerRoles": "", "pendingMattersId": 37, "processingTime": 1627308319000, "stateId": 1, "stateName": null, "status": 1},
            // {"applicationTime": 1627308319000, "caseCode": "51152420210000101131", "caseTextId": null, "currentHandler": {"administrativeQualificationCertificateNumber": "川Q05660097", "isOnline": false, "latitude": 28.5847, "longitude": 104.93071, "name": "刘艳", "officerId": 15}, "currentHandlerDept": 42, "currentHandlerId": 15, "expireTime": 1627358384000, "handlerOpinions": "111231", "id": 107, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "审核批准", "linkId": 128, "linkName": "中队一般案件审核", "nextHandlerDepts": "41", "nextHandlerOfficers": "罗龙,魏东", "nextHandlerRoles": "6,7", "pendingMattersId": 37, "processingTime": 1627308362000, "stateId": 1, "stateName": null, "status": 1}, {"applicationTime": 1627308362000, "caseCode": "51152420210000101131", "caseTextId": null, "currentHandler": {"administrativeQualificationCertificateNumber": "川Q05890002", "isOnline": false, "latitude": 28.58831, "longitude": 104.93033, "name": "罗龙", "officerId": 23}, "currentHandlerDept": 41, "currentHandlerId": 23, "expireTime": 1627358428000, "handlerOpinions": "131313413", "id": 108, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "提出立案", "linkId": 2, "linkName": "处罚中队立案承办", "nextHandlerDepts": "41", "nextHandlerOfficers": "罗龙", "nextHandlerRoles": null, "pendingMattersId": 37, "processingTime": 1627308439000, "stateId": 2, "stateName": null, "status": 1}, {"applicationTime": 1627308439000, "caseCode": "51152420210000101131", "caseTextId": null, "currentHandler": {"administrativeQualificationCertificateNumber": "川Q05890002", "isOnline": false, "latitude": 28.58831, "longitude": 104.93033, "name": "罗龙", "officerId": 23}, "currentHandlerDept": 41, "currentHandlerId": 23, "expireTime": 1627358505000, "handlerOpinions": "1234124", "id": 109, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "立案审核", "linkId": 15, "linkName": "中队长立案初审", "nextHandlerDepts": "36", "nextHandlerOfficers": "李小军", "nextHandlerRoles": "", "pendingMattersId": 37, "processingTime": 1627308550000, "stateId": 2, "stateName": null, "status": 1}, {"applicationTime": 1627308550000, "caseCode": "51152420210000101131", "caseTextId": null, "currentHandler": {"administrativeQualificationCertificateNumber": "08260114", "isOnline": false, "latitude": 28.58838, "longitude": 104.93003, "name": "李小军", "officerId": 20}, "currentHandlerDept": 36, "currentHandlerId": 20, "expireTime": 1627358615000, "handlerOpinions": "13413413", "id": 110, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "立案审批", "linkId": 118, "linkName": "大队立案审核", "nextHandlerDepts": "38", "nextHandlerOfficers": "陈家莲", "nextHandlerRoles": "", "pendingMattersId": 37, "processingTime": 1627308670000, "stateId": 2, "stateName": null, "status": 1}, {"applicationTime": 1627308670000, "caseCode": "51152420210000101131", "caseTextId": null, "currentHandler": {"administrativeQualificationCertificateNumber": "", "isOnline": false, "latitude": null, "longitude": null, "name": "陈家莲", "officerId": 22}, "currentHandlerDept": 38, "currentHandlerId": 22, "expireTime": 1627358736000, "handlerOpinions": "123456", "id": 111, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "立案审批", "linkId": 119, "linkName": "案管科立案审核", "nextHandlerDepts": "1", "nextHandlerOfficers": "宋富江", "nextHandlerRoles": "10", "pendingMattersId": 37, "processingTime": 1627308765000, "stateId": 2, "stateName": null, "status": 1}, {"applicationTime": 1627308765000, "caseCode": "51152420210000101131", "caseTextId": null,
            // "currentHandler": {"administrativeQualificationCertificateNumber": "", "isOnline": false, "latitude": 30.62598, "longitude": 103.99063, "name": "宋富江", "officerId": 19}, "currentHandlerDept": 1, "currentHandlerId": 19, "expireTime": 1627358830000, "handlerOpinions": "121213", "id": 112, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "审批通过", "linkId": 120, "linkName": "分管领导立案审批", "nextHandlerDepts": "40,41,42,43,44", "nextHandlerOfficers": "刘艳,罗龙,李旭东", "nextHandlerRoles": "6,7,3", "pendingMattersId": 37, "processingTime": 1627308849000, "stateId": 2, "stateName": null, "status": 1}, {"applicationTime": 1627308849000, "caseCode": "51152420210000101131", "caseTextId": null, "currentHandler": {"administrativeQualificationCertificateNumber": "川Q05660097", "isOnline": false, "latitude": 28.5847, "longitude": 104.93071, "name": "刘艳", "officerId": 15}, "currentHandlerDept": 42, "currentHandlerId": 15, "expireTime": 1627358914000, "handlerOpinions": null, "id": 113, "isBranch": 0, "isEffective": null, "linkHandleId": null, "linkHandleName": "暂存", "linkId": 113, "linkName": "调查取证", "nextHandlerDepts": "40,41,42,43,44", "nextHandlerOfficers": "刘艳,罗龙,李旭东", "nextHandlerRoles": "6,7,3", "pendingMattersId": 37, "processingTime": 1627309665000, "stateId": 3, "stateName": null, "status": 1}]
            // views.push((<Steps>));
            let steps = []
            list.map((item,index) => {
                let time = new Date(item.applicationTime).Format('yyyy-MM-dd hh:mm:ss')
                let linkName = item.linkName + "【" + item.linkHandleName + "】"
                steps.push(<Step
                    title={linkName}
                    description={<View>
                            <Text>办理人：{item.currentHandler?item.currentHandler.name: '- -'}</Text>
                            <Text>意见：{item.handlerOpinions ||  '- -'}</Text>
                            <Text>{time}</Text>
                    </View>}
                    renderIcon={()=>{
                        return (
                            <Text style={{color: '#fff',fontSize: 14,textAlign: 'center'}}>{index+1}</Text>
                        )
                    }}
                >
                    <Text>{item.handlerOpinions}</Text>
                </Step>)
            });
            views.push(<Steps current={list.length}>
                {steps}
            </Steps>)
        }else{
            views.push(
                <View key={'no-data'}>
                    <Text style={{textAlign: 'center',fontSize: 16}}>暂无办理结果</Text>
                </View>
            )
        }

        return (
            // <FlatList
            //     style={styles.list}
            //     data={list}
            //     keyExtractor={(item, index) => `action_record_${index}`}
            //     renderItem={(data) => this._renderDealLogItem(data)}
            // />
            <ScrollView style={{padding: 10}}>
                {views}
            </ScrollView>
        )

        // return (
        //     <View>
        //         <Text>处理记录</Text>
        //     </View>
        // )
    }
    _renderDealLogItem(data){
        let {item} = data;
        let {linkName,linkHandleName} = item;
        return (
            <TouchableOpacity>
                <View>
                    <Text>{linkName}【{linkHandleName}】</Text>
                </View>
            </TouchableOpacity>
        )
    }
    _renderUpdateDocument(){
        let {activeBtns, documentBtnList, casePendingMatter, documentType} = this.state
        let views = []
        let documentsStr =  casePendingMatter.documentRequired || ''
        if(documentsStr){
            let documents = JSON.parse(documentsStr)
            documents.map((item,index)=>{
                views.push(
                    <View key={index+'_document_file'} style={{width: screenWidth/2 - 30,alignItems: 'center',marginBottom: 15}}>
                        <ImageBackground
                            key={index}
                            style={{width: 144,height: 186,alignItems: 'center',padding: 20,paddingTop: 20}}
                            source={require('../../../assets/images/report/document_bg.png')}
                        >
                            {/*24 * 6 31*/}
                            <Text style={{color: '#fff',fontSize: 16,textAlign: 'center',paddingTop: 25}}>{item.name}</Text>
                        </ImageBackground>
                    </View>
                )
            })
        }
        let btns = []
        documentBtnList.map((item,index)=>{
            btns.push(
                <TouchableOpacity
                    key={index + '_document_btn'}
                    style={[styles.chooseItem,activeBtns.includes(item.id)?styles.chooseActiveItem:'']}
                    onPress={()=>this._changeActiveBtns(item)}
                >
                    <Text style={[styles.chooseItemLabel,activeBtns.includes(item.id)?styles.labelActive:'']}>{item.name}</Text>
                </TouchableOpacity>
            )
        })
        let nextLinks=this.state.nextLinks
        return (<View>
            <View style={{flex: 1,paddingTop: 10,paddingBottom: 10}}>
                <View style={{flexDirection: 'row',flexWrap: 'wrap'}}>
                    {btns}
                </View>
                {casePendingMatter.name?(
                    <View>
                        <List>
                            {/* <InputItem
                                value={casePendingMatter.linkName}
                                maxLength={50}
                                editable={false}
                                labelNumber={4}
                                readonly={true}>
                                <Text style={{fontSize:14,width:40}}>名称</Text>
                                
                            </InputItem> */}
                            {nextLinks
                                ?
                                <TextInputItem
                                 label={"名称"}
                                 placeholder={"请输入名称"}
                                 maxLength={50}
                                 value={casePendingMatter.linkName}
                                 isBack={true}
                                 labelWidth={120}
                                 onChange={(text)=>{
                                     let data=Object.assign({},this.state.casePendingMatter,{linkName:text})
                                     this.setState({
                                         casePendingMatter:data
                                     })
                                 }} />
                                :null
                            }
                          
                            {/* value={casePendingMatter.nextHandlerDeptName} */}
                            {/* 部门 */}
                            {casePendingMatter.linkName&&nextLinks?                                <FormItem
                                 label={'办理部门'}
                                 labelWidth={120}
                                 value={casePendingMatter.nextHandlerDeptName}
                                 placeholder={'请选择办理部门'}
                                 maxLength={50}
                                 onClick={() => {
                                     this.showDeptActionSheet()
                                 }}
                             />:null
                            }
                           
                           {casePendingMatter.linkName&&nextLinks?                                <FormItem
                                    label={'办理角色'}
                                    labelWidth={120}
                                    value={casePendingMatter.nextHandlerRoleName}
                                    placeholder={'请选择办理角色'}
                                    maxLength={50}
                                    onClick={() => {
                                        this.showRoleActionSheet()
                                    }}
                                />
                           :null}
                            
                            {casePendingMatter.linkName&&nextLinks?
                                <FormItem
                                    label={'下环节处理人'}
                                    labelWidth={120}
                                    value={casePendingMatter.nextHandlerOfficerNames}
                                    placeholder={'请选择处理人'}
                                    maxLength={50}
                                    onClick={() => {
                                        this.showOfficeActionSheet()
                                    }}
                                />
                            :null}
                            
                            <FormItem
                                label={'常用短语'}
                                labelWidth={120}
                                value={casePendingMatter.msg2}
                                placeholder={'请选择常用短语'}
                                maxLength={50}
                                onClick={() => {
                                    this.showMsgActionSheet('report')
                                }}
                            />
                            {/*处理意见*/}
                            <View style={{
                                flexDirection: 'row',justifyContent: 'space-between',alignItems: 'center',
                                paddingLeft: 15,paddingRight: 15,paddingTop: 5,paddingBottom: 5,
                            }}>
                             <Text style={{fontSize: 14}}>处理意见</Text>
                            </View>
                            <TextareaItem
                                rows={4}
                                maxLength={100}
                                value={casePendingMatter.caseActionRecord.handlerOpinions}
                                onChange={(value) => this._changeOpinions(value)}
                                placeholder="请输入处理意见"
                                style={{ paddingVertical: 5,marginLeft: 15,backgroundColor: 'rgba(245, 245, 245, 0.43)',fontSize:14 }}
                            />
                        </List>

                    </View>
                ):null}
                {/*<View style={{padding: 10,flexDirection: 'row',flexWrap: 'wrap'}}>*/}
                    {/*{views}*/}
                {/*</View>*/}
            </View>
        </View>)
    }

    _renderCaseForm(){
        let { inspectionPendingMatter } = this.state
        let OfficerList=this.state.inspectionPendingMatter.nextHandlerOfficerList
        return (
            <View>
                <View style={{flex: 1,paddingTop: 10,paddingBottom: 10}}>
                    <View>
                        <List>
                            {/*<View style={{paddingTop: 8}}>*/}
                            {/*    <Text style={{fontSize: 16}}>巡查任务</Text>*/}
                            {/*</View>*/}
                            {/* <InputItem
                                value={inspectionPendingMatter.linkName}
                                maxLength={50}
                                editable={false}
                                labelNumber={6}
                                readonly={true}>
                                <Text style={{fontSize:14,width:100}}>下环节名称</Text>
                            </InputItem> */}
                              {/* { 
                                OfficerList&&OfficerList.length>0?
                                ''
                                :
                                ''} */}
                            <TextInputItem
                                label={"下环节名称"}
                                placeholder={"请输入下环节名称"}
                                maxLength={50}
                                value={inspectionPendingMatter.linkName}
                                isBack={true}
                                labelWidth={120}
                                onChange={(text)=>{
                                    let data=Object.assign({},this.state.inspectionPendingMatter,{linkName:text})
                                    this.setState({
                                        inspectionPendingMatter:data
                                    })
                                }}
                            />
                           
                            { 
                                OfficerList&&OfficerList.length>0?
                                <FormItem
                                    label={'下环节处理人'}
                                    labelWidth={120}
                                    value={inspectionPendingMatter.nextHandlerOfficerNames}
                                    placeholder={'请选择处理人'}
                                    maxLength={50}
                                    onClick={() => {
                                        this.showCaseOfficeActionSheet()
                                    }}
                                />
                                :null
                            }
                         


                            <FormItem
                                label={'常用短语'}
                                labelWidth={120}
                                value={inspectionPendingMatter.msg2}
                                placeholder={'请选择常用短语'}
                                maxLength={50}
                                onClick={() => {
                                    this.showMsgActionSheet('task')
                                }}
                            />
                            {/*处理意见*/}
                            <View style={{
                                flexDirection: 'row',justifyContent: 'space-between',alignItems: 'center',
                                paddingLeft: 15,paddingRight: 15,paddingTop: 5,paddingBottom: 5,
                            }}>
                                <Text style={{fontSize: 14}}>处理意见</Text>
                            </View>
                            <TextareaItem
                                rows={4}
                                maxLength={100}
                                value={inspectionPendingMatter.caseActionRecord.handlerOpinions}
                                onChange={(value) => this._changeCaseOpinions(value)}
                                placeholder="请输入处理意见"
                                style={{ paddingVertical: 5,marginLeft: 15,backgroundColor: 'rgba(245, 245, 245, 0.43)',fontSize:14 }}
                            />

                        </List>
                    </View>
                </View>
            </View>
        )
    }
    _changeCaseOpinions(value){
        this.state.inspectionPendingMatter.caseActionRecord.handlerOpinions = value
        this.setState({inspectionPendingMatter: this.state.inspectionPendingMatter});
        this.props.onChange && this.props.onChange({
            inspectionPendingMatter: this.state.inspectionPendingMatter,
            casePendingMatter: this.state.casePendingMatter
        })
    }
    _changeOpinions(value){
        this.state.casePendingMatter.caseActionRecord.handlerOpinions = value
        this.setState({casePendingMatter: this.state.casePendingMatter});
        this.props.onChange && this.props.onChange({
            inspectionPendingMatter: this.state.inspectionPendingMatter,
            casePendingMatter: this.state.casePendingMatter
        })
    }
    showCaseOfficeActionSheet(){
        let list = this.state.inspectionPendingMatter.nextHandlerOfficerList
        let labels = list.map((item) => item.name);
        labels.push('关闭');
        let values = list.map((item) => item.officerId);
        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
                height: 300
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }
                let data = Object.assign({}, this.state.inspectionPendingMatter, {
                    nextHandlerOfficerNames: labels[index],
                    nextHandlerOfficerIds: [values[index]],
                });
                this.setState({inspectionPendingMatter: data});
                this.props.onChange && this.props.onChange({
                    inspectionPendingMatter: this.state.inspectionPendingMatter,
                    casePendingMatter: this.state.casePendingMatter
                })
                // fn && fn(values[index])
            },
        );
    }

    //常用短语
    showMsgActionSheet(type){
        let list = this.state.shortMsgList
        let labels = list.map((item) => item.name);
        labels.push('关闭');
        let values = list.map((item) => item.content);

        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
                height: 300
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }

                if(type=='task'){//巡查任务
                    let data1 = Object.assign({}, this.state.inspectionPendingMatter.caseActionRecord, {
                        handlerOpinions: values[index],
                    });
    
                    let data = Object.assign({}, this.state.inspectionPendingMatter, {
                        caseActionRecord:data1,
                        msg2:labels[index] ,
                    });
    
                    this.setState({inspectionPendingMatter: data});
                    this._changeCaseOpinions(values[index])
                }else{ //巡查上报
                    let data1 = Object.assign({}, this.state.casePendingMatter.caseActionRecord, {
                        handlerOpinions: values[index],
                    });
    
                    let data = Object.assign({}, this.state.casePendingMatter, {
                        caseActionRecord:data1,
                        msg2:labels[index] ,
                    });
    
                    this.setState({casePendingMatter: data});
                    this._changeOpinions(values[index])
                }
                
                // fn && fn(values[index])
            },
        );
    }

    showOfficeActionSheet(){
        let list = []
        let deptIds=this.state.casePendingMatter.nextHandlerDeptIds&&this.state.casePendingMatter.nextHandlerDeptIds.length>0
        let roleIds=this.state.casePendingMatter.nextHandlerRoleIds&&this.state.casePendingMatter.nextHandlerRoleIds.length>0
        if(deptIds||roleIds){
            list=this.state.nextHandlerOfficerList
        }else{
            list=this.state.casePendingMatter.nextHandlerOfficerList
        }

        let labels = list.map((item) => item.name);
        labels.push('关闭');
        let values = list.map((item) => item.officerId);
        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }
                let data = Object.assign({}, this.state.casePendingMatter, {
                    nextHandlerOfficerNames: labels[index],
                    nextHandlerOfficerIds: [values[index]],
                });
                this.setState({casePendingMatter: data});
                this.props.onChange && this.props.onChange({
                    inspectionPendingMatter: this.state.inspectionPendingMatter,
                    casePendingMatter: data
                })
                // fn && fn(values[index])
            },
        );
    }

    // 部门
    async   showDeptActionSheet(){
        await this.setState({showTypePop: !this.state.showTypePop})
    }
    
    // 角色
    showRoleActionSheet(){
        let list = this.state.casePendingMatter.nextHandlerRoleList
        let labels = list.map((item) => item.name);
        labels.push('关闭');
        let values = list.map((item) => item.id);
        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }
                let that=this
                let data = Object.assign({}, that.state.casePendingMatter, {
                    nextHandlerRoleName: labels[index],
                    nextHandlerRoleIds: [values[index]],
                });
               
                that.setState({casePendingMatter: data});
                that.props.onChange && that.props.onChange({
                    inspectionPendingMatter: that.state.inspectionPendingMatter,
                    casePendingMatter: data
                })
                
                setTimeout(()=>{
                    this._avoidNextPerson()
                },100)
            },
        );
    }
    render() {
        let {documentType} = this.state
        // inspection
        let {reportType, submitType,showTypePop} = this.props
        return (
            <View style={[GlobalStyles.innerTabPanel,{flexDirection: 'column',flex: 1}]}>
                {this._renderHeaderBtns()}
                <ScrollView
                    style={{flex: 1}}
                    automaticallyAdjustContentInsets={false}
                    showsHorizontalScrollIndicator={false}
                    showsVerticalScrollIndicator={false}>
                    {documentType === '2' ?
                        ( submitType === 'post' ? this._renderCaseForm()
                                :this._renderDealLog()
                        ):this._renderUpdateDocument()
                    }
                </ScrollView>
                {this._custonDig()}
            </View>
        );
    }
    _custonDig(){
        let {DeptArr}=this.state
        return (DeptArr&&DeptArr.length>0?<CustomAlertDialog 
            entityList={DeptArr}
            callback={(data) => {
                let obj={}
                obj.nextHandlerDeptIds=[data.id]
                obj.nextHandlerDeptName=data.name
                let query=Object.assign({},this.state.casePendingMatter,obj)
                this.setState({
                    casePendingMatter:query
                })
                setTimeout(()=>{
                    this._avoidNextPerson()
                },100)
            }} 
            show={this.state.showTypePop} closeModal={(show) => {
                this.setState({
                    showTypePop: show
                })
            }}
        />:null)
    }

    // 选择发布类型
    showIndustryTypeActionSheet() {
        this.showDictActionSheet('case_related_industries','caseRelatedIndustriesLabel','caseRelatedIndustries',(value)=>{
            this._queryCheckAndXunchaList(value)
        })
    }
    async showDictActionSheet(key,label,value,fn){
        let dict = await Dict.getDict(key);
        let labels = dict.map((item) => item.label);
        labels.push('关闭');
        let values = dict.map((item) => item.value);
        ActionSheet.showActionSheetWithOptions(
            {
                options: labels,
                destructiveButtonIndex: labels.length - 1,
                maskClosable: true,
            },
            (index) => {
                if (labels[index] === '关闭') {
                    return false;
                }
                let data = Object.assign({}, this.state.caseInfoVo, {
                    [label]: labels[index],
                    [value]: values[index],
                });
                this.setState({caseInfoVo: data});
                fn && fn(values[index])
            },
        );
    }

    _renderHeaderBtns(){
        let {documentType} = this.state
        let {submitType} = this.props
        return (
            <View style={{flexDirection: 'row'}}>
                <TouchableOpacity
                    style={[
                        {flex: 1,justifyContent: 'center',borderTopLeftRadius: 5,borderBottomLeftRadius: 5,padding: 8},
                        documentType==='1'?{ backgroundColor: '#4D70CC' }: {borderColor: '#4D70CC',borderWidth: 1}
                    ]}
                    onPress={()=>{
                        if(this.state.documentType === '2'){
                            this.setState({
                                documentType: '1'
                            })
                        }
                    }}
                >
                    <Text style={[
                        {textAlign: 'center'},
                        documentType==='1'?{ color: '#fff' }:{color: '#4D70CC'}
                    ]}>业务办理</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={[
                        {flex: 1,justifyContent: 'center',borderTopRightRadius: 5,borderBottomRightRadius: 5,padding: 8},
                        documentType==='2'?{ backgroundColor: '#4D70CC' }: {borderColor: '#4D70CC',borderWidth: 1}
                    ]}
                    onPress={()=>{
                        if(this.state.documentType === '1'){
                            this.setState({
                                documentType: '2'
                            })
                        }
                    }}
                >
                    <Text style={[
                        {textAlign: 'center'},
                        documentType==='2'?{ color: '#fff' }: {color: '#4D70CC'}
                    ]}>
                        {submitType==='post'?'巡查任务':'办理记录'}
                    </Text>
                </TouchableOpacity>
            </View>
        )
    }

}

let styles = StyleSheet.create({
    chooseItem:{
        paddingTop: 5,
        paddingBottom: 5,
        paddingLeft: 10,
        paddingRight: 10,
        borderWidth: 1,
        borderColor: 'rgba(224, 224, 224, 1)',
        borderRadius: 5,
        marginLeft: 12,
        marginBottom: 12
    },
    chooseItemLabel:{
        color: '#8F8F8F',
        fontSize: 14,
    },
    chooseActiveItem: {
        backgroundColor: 'rgba(77, 112, 204, 0.17)',
        borderColor: '#4D70CC'
    },
    labelActive:{
        color: '#4D70CC',
    },
})
